package com.skydroid.serialport

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.skydroid.fpvlibrary.common.connect.serialport.SerialPortConnection
import kotlin.experimental.xor

class DataSamplesActivity : AppCompatActivity(){
    private var context : Context? = null

    private var tvReceive: TextView? = null

    private var tvSend: TextView? = null

    private var headerArray = "fengyingdianzi:".toByteArray()

    //串口实例
    private var mSerialPortConnection: SerialPortConnection? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_data_samples)
        context = this
        initView()
        initData()
    }

    companion object{
        fun start(context : Context?){
            context?.startActivity(Intent(context,DataSamplesActivity::class.java))
        }
    }

    private fun initView(){
        findViewById<View>(R.id.btn_send).setOnClickListener {
            val sb = StringBuilder()
            sb.append(String2ByteArrayUtils.bytes2Hex("fengyingdianzi:".toByteArray()))
                .append("A9")
                .append(String2ByteArrayUtils.byte2Hex(2.toByte()))
                .append(String2ByteArrayUtils.bytes2Hex("R".toByteArray()))
                .append(String2ByteArrayUtils.byte2Hex(1.toByte()))
            sb.append(String2ByteArrayUtils.byte2Hex(getBCC(sb.toString())))
            tvSend?.text = sb.toString()
            mSerialPortConnection?.sendData(String2ByteArrayUtils.hex2Bytes(sb.toString()))
        }

        tvReceive = findViewById(R.id.tv_receive)
        tvSend = findViewById(R.id.tv_send)
    }

    private fun initData(){
        mSerialPortConnection =
            SerialPortConnection(
                921600,
                "/dev/ttyHSL1"
            )
        mSerialPortConnection?.setDelegate(object : SerialPortConnection.Delegate{
            override fun received(bytes: ByteArray?, size: Int) {
                runOnUiThread {
                    //判断帧头
                    if(String2ByteArrayUtils.bytes2Hex(bytes)?.contains(String2ByteArrayUtils.bytes2Hex(headerArray)?:"") == true){
                        Log.e("DataSamplesActivity","接收:${String2ByteArrayUtils.bytes2Hex(bytes)}")
                        tvReceive?.text = String2ByteArrayUtils.bytes2Hex(bytes)
                    }

                }
            }
        })

    }

    /**
     * 16进制字符串
     */
    fun getBCC(s: String): Byte {
        var data = String2ByteArrayUtils.hex2Bytes(s)!!
        var temp = data[0]
        for (i in 1 until data.size) {
            temp = temp xor data[i]
        }
        return temp
    }

    override fun onDestroy() {
        super.onDestroy()
        mSerialPortConnection?.closeConnection()
    }
}